<?php

namespace app\shop\controller;

use app\shop\model\ShopGoodsSpecs;
use app\shop\model\ShopStoreGoodsSpecs;
use buildView\Filter;
use buildView\Form;
use buildView\Grid;
use library\Controller;

/**
 * 规格管理
 * Class StoreSpec
 * @package app\store\controller
 * @author
 * @date 2018/7/27
 */
class StoreSpec extends Controller
{
    /**
     * 规格列表
     * @auth true
     * @mentu true
     * @return string
     */
    public function index()
    {
        $grid = new Grid(new ShopStoreGoodsSpecs());
        $grid->setTitle('规格管理（请勿随意修改或删除）');
        $grid->title('规格分组');
        $grid->param('规格内容')->display(function ($val, $data) {
            $arrays = json_decode($val, true);
            $html = '';
            foreach ($arrays as $array) {
                $html .= '<b>' . $array['name'] . '</b> : ' . $array['value'] . '<br>';
            }
            return $html;
        })->align('left');
        $grid->status('状态')->switchs([
            'on' => ['text' => '使用中', 'value' => 1],
            'off' => ['text' => '禁用', 'value' => -1],
        ]);
        $grid->create_at('添加时间');
        $grid->filter(function (Filter $filter) {
            $filter->like('spec_title', '规格分组');
            $filter->dateBetween('create_at', '添加时间');
        });
        $grid->actions(function ($action) {
            $action->hideDetail();
        });
        $grid->hideExportButton();
        $grid->setFromOpen();
        return $grid->view();
    }

    /**
     * 添加/编辑
     * @auth true
     * @mentu true
     * @return string
     */
    public function form()
    {
        $form = new Form(new ShopStoreGoodsSpecs());
        $form->text('title', '规格分组')->required();
        $form->specs('param', '规格参数');
        $form->textarea('desc', '描述');
        $form->saving(function ($post) {
            $spec_name = $post['spec_name'];
            $specs = [];
            foreach ($spec_name as $key => $value) {
                $specs[$key]['name'] = $value;
                $specs[$key]['value'] = $post['spec_value'][$key];
            }
            $post['param'] = json_encode($specs, JSON_UNESCAPED_UNICODE);
            return $post;
        });
        return $form->view();
    }
}
